package app.gpwars.engine;
// Copyright 2010 owners of the AI Challenge project
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy
// of the License at http://www.apache.org/licenses/LICENSE-2.0 . Unless
// required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
//
// Author: Jeff Cameron (jeff@jpcameron.com)
//
// Plays a game of Planet Wars between two computer programs.

import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import app.gpwars.engine.bots.BotFactory;


public class Engine {

	private int numTurns;

	public int runGame(Game game, Player gpPlayer, List<String> bots, boolean verbose) {
		numTurns = 0;

		//List of players
		List<Player> players = new ArrayList<Player>();
		//List of orders issued by a player
		List<Order> playerOrders = new ArrayList<Order>();

		//Init players: The first player is always the individual generated by GP:
		int playerID = 1;
		gpPlayer.setID(playerID++);
		players.add(gpPlayer);
		for (String bot : bots) {
			players.add(BotFactory.makeBot(bot, playerID++));
		}

		try {
			PrintWriter viewerOut = null;
			if (verbose) {
				viewerOut = new PrintWriter(new FileWriter("src/app/gpwars/alternativeViewerLog.txt"));
			}
			// Enter the main game loop.
			while (game.Winner() < 0) {

				for (int i = 0; i < players.size(); i++) {
					Player player = players.get(i); 
					playerOrders = player.DoTurn(game);
					for (Order order : playerOrders) {
						game.issueOrder(player, order);
					}
				}

				++numTurns;
				if (verbose) {
					viewerOut.println(game.FlushGamePlaybackString());
				}
				game.DoTimeStep();
			}

			if (verbose) {
				viewerOut.println(game.GamePlaybackString());
				viewerOut.close();
			}


		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return game.Winner();

	}

	public int getNumTurns() {
		return numTurns;
	}	

}
